/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import models.Chat;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Vuong Pham<Vuong.Pham@hva.nl>
 */
public class ChatDao {
    
    private final Session session;

    public ChatDao(Session session) {
        this.session = session;
    }

    public List<Chat> findAll() {
        Transaction tx = session.beginTransaction();
        List<Chat> list = session.createQuery("from Chat as c").list();
        tx.commit();
        return list;
    }
    
    //get chat obejcts by the lesson id (and type (question or chat))
    public List<Chat> findAllByLesson(long lessonid, String type) { 
        Transaction tx = session.beginTransaction();
        List<Chat> list = session.createQuery("from Chat where lesson_lesson_id= :id AND type= :type").setParameter("id", lessonid).setParameter("type", type).list();
        tx.commit();
        return list;
    }
    
    //get the chat objects by the lessonid
    public List<Chat> spamChecker(long lessonid) {
        Transaction tx = session.beginTransaction();
        List<Chat> list = session.createQuery("from Chat where lesson_lesson_id= :id ORDER BY id DESC LIMIT 5 ").setParameter("id", lessonid).list();
        tx.commit();
        return list;
    }

    public boolean save(Chat chat) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(chat);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean update(Chat chat) {
        try {
            Transaction tx = session.beginTransaction();
            session.update(chat);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public Chat get(long id) {
        return (Chat) session.get(Chat.class, id);
    }

    public void delete(Chat chat) {
        Transaction tx = session.beginTransaction();
        session.delete(chat);
        tx.commit();
    }
}
